package com.example.iotmanagerment26.service.impl;

import com.example.iotmanagerment26.service.MoneyService;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@Service
@EnableAsync
public class MoneyServiceImpl implements MoneyService {

    // 使用AtomicReference保证线程安全
    private final AtomicReference<Order> currentOrder = new AtomicReference<>(null);
    private final RestTemplate restTemplate = new RestTemplate();
    private static final String API_URL = "http://129.204.4.65:8089/businessCenter/v1/action/actjson";
    private static final String DEVICE_ID = "b8:27:eb:a3:e6:dc";
    private static final String DEVICE_TYPE = "rpi";
    private static final String UNIT = "60";
    private static final String ACTION = "1";
    private int gy=0;

    // 订单类，用于保存订单信息
    private static class Order {
        private final String room;
        private final int money;
        private final LocalDateTime createTime;

        public Order(String room, int money) {
            this.room = room;
            this.money = money;
            this.createTime = LocalDateTime.now();
        }

        public String getRoom() {
            return room;
        }

        public int getMoney() {
            return money;
        }

        public LocalDateTime getCreateTime() {
            return createTime;
        }
    }

    @Override
    public int submit(String room, int money) {
        this.gy=0;
        // 检查是否已有未结算的订单
        Order existingOrder = currentOrder.get();
        if (existingOrder != null) {
            // 发送"请先结算当前的订单！"通知
            sendNotification(room + "请先结算当前的订单！");
            return -1; // 返回-1表示已有订单，提交失败
        }

        // 创建新订单
        Order newOrder = new Order(room, money);
        if (currentOrder.compareAndSet(null, newOrder)) {
            // 发送"有订单待结算！"通知
            sendNotification(room + "有订单待结算！");
            return 1; // 返回1表示提交成功
        } else {
            // 并发情况下可能设置失败
            sendNotification(room + "请先结算当前的订单！");
            return -1;
        }
    }

    @Override
    public int induction() {
        this.gy=1;
        return 1;
    }

    @Override
    public Map<String,Object> getInduction() {
        Map<String,Object> induction = new HashMap<>();
        Order order = currentOrder.get();
        induction.put("induction",this.gy);
        if(order!=null){
            induction.put("room",order.getRoom());
            induction.put("money",order.getMoney());
        }
        return induction;
    }

    @Override
    public int pay() {
        this.gy=0;
        Order order = currentOrder.getAndSet(null);
        if (order != null) {
            // 发送结算成功通知
            sendNotification(order.getRoom() +"结算成功！   结算金额:"+ order.getMoney() + "元！");
            return 1; // 返回0表示结算成功
        } else {
            return -1; // 返回-1表示没有待结算的订单
        }
    }

    // 每30秒执行一次，检查订单状态
    @Scheduled(fixedRate = 30 * 1000)
    @Async
    public void checkOrderStatus() {
        Order order = currentOrder.get();
        if (order != null) {
            // 计算订单创建时间到现在的分钟数
            long minutes = java.time.Duration.between(order.getCreateTime(), LocalDateTime.now()).toMinutes();
            if (minutes >= 5) {
                // 订单超过5分钟未结算，自动取消
                if (currentOrder.compareAndSet(order, null)) {
                    sendNotification(order.getRoom() + "订单已取消！");
                    this.gy=0;
                }
            } else {
                // 订单未超时，发送待结算通知
                sendNotification(order.getRoom() + "有订单待结算！");
                this.gy=0;
            }
        }
    }

    // 发送通知到指定API
    private void sendNotification(String content) {
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构建请求体
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("devid", DEVICE_ID);
        requestBody.put("types", DEVICE_TYPE);
        requestBody.put("unit", UNIT);
        requestBody.put("act", ACTION);
        requestBody.put("content", content);

        // 发送请求
        HttpEntity<Map<String, String>> request = new HttpEntity<>(requestBody, headers);
        ResponseEntity<String> response = restTemplate.postForEntity(API_URL, request, String.class);

        // 可以添加日志记录响应结果
        if (response.getStatusCode() == HttpStatus.OK) {
            System.out.println("通知发送成功: " + content);
        } else {
            System.out.println("通知发送失败: " + content + ", 状态码: " + response.getStatusCode());
        }
    }
}